<?php
/**
 * shouse service
 */
namespace App\Service;

use Phalcon\Di;
use App\Models\Loupan;
use App\Models\EwHouse;

class ShouseService  extends BaseService
{
	const MIGRATE_TRUE = 1;		//入库标识：是
	const MIGRATE_FALSE = 0;	//入库标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	/**
	 * [getList 列表 列表]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getList($params, $count = FALSE)
	{
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['l.id,l.title,l.url,l.source_site,l.price,l.thumb,l.developers,l.region,l.address,l.property,l.units,l.open_time,l.launch_time,l.sales_address,l.households,l.car_number']);
		$builder->addFrom("App\Models\Loupan", 'l');
		$builder->andWhere("l.is_del = " . self::DEL_FALSE);

		//is_migrate 
		if (isset($params->is_migrate))
			$builder->andWhere("l.is_migrate = ". $params->is_migrate);

		//title
		if (isset($params->title) && $params->title)
			$builder->andwhere("l.title LIKE '%" . $params->title . "%'");

		//min_price 价格
		if (isset($params->min_price) && $params->min_price)
			$builder->andwhere('l.price > ' . $params->min_price);

		//max_price 价格
		if (isset($params->max_price) && $params->max_price)
			$builder->andwhere('l.price < ' . $params->max_price);

		//developers 开发商
		if (isset($params->developers) && $params->developers)
			$builder->andwhere("l.developers LIKE '%" . $params->developers . "%'");

		//sources
		if (isset($params->sources) && $params->sources)
			$builder->andwhere("l.source_site LIKE '%" . $params->sources . "%'");
		
		//source_site 来源
		if (isset($params->source_site) && $params->source_site)
			$builder->andwhere("l.source_site LIKE '%" . $params->source_site . "%'");

		//property
		if (isset($params->property) && $params->property)
			$builder->andwhere("l.property LIKE '%" . $params->property . "%'");

		//region
		if (isset($params->region) && $params->region)
			$builder->andwhere("l.region LIKE '%" . $params->region . "%'");

		//address
		if (isset($params->address) && $params->address)
			$builder->andwhere("l.address LIKE '%" . $params->address . "%'");

		//sales_address
		if (isset($params->sales_address) && $params->sales_address)
			$builder->andwhere("l.sales_address LIKE '%" . $params->sales_address . "%'");

		//property
		if (isset($params->property) && $params->property)
			$builder->andwhere("l.property LIKE '%" . $params->property . "%'");

		//units
		if (isset($params->units) && $params->units)
			$builder->andwhere("l.units LIKE '%" . $params->units . "%'");

		//count 数量
		if ($count)
			return $builder->getQuery()->execute()->count();

		//order_by 排序
		if (isset($params->order_by)){
			$sql = parent::orderBy($params->order_by, $table = "l");
		}else{
			$sql = " l.id DESC";
		}
		$builder->orderBy($sql);

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();
		return $result->execute();	
	}

	/**
	 * [getInfo 详情]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function getInfo($id)
	{
		return Loupan::findFirst($id);
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = Loupan::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [forever 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = Loupan::findFirst($id);

		if ($row && $row->delete())
			return TRUE;

		return NULL;
	}

	/**
	 * [migrate 入库]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function migrate($id)
	{

		$info = Loupan::findFirst($id);

		if (!$info || $info->is_migrate == self::MIGRATE_TRUE)
			return NULL;
		//过滤 \n
		foreach ($info as $key => $value) {
			$info->$key = preg_replace("/\\n/", "", $value);
			$info->$key = trim($info->$key);
		}
		//http://cd.fang.anjuke.com/loupan/415527.html 
		//http://m.anjuke.com/cd/loupan/415527/ 
		//url
		$old_url = $info->url;
		$str = str_replace("http://cd.fang.anjuke.com/loupan/","",$old_url);
		$str = str_replace(".html","",$str);
		$m_url = "http://m.anjuke.com/cd/loupan/";
		$three_url = $m_url . $str . '/';

		$price = "";
		if (intval($info->price) == 0){
			$price = "售价待定";
		}else if (intval($info->price) > 3000 ){
			$price = intval($info->price) . ' 元/㎡';
		}else{
			$price = intval($info->price) . ' 万';
		}
		//成都天府城南谷底湖湿地公园（新普路南侧）[查看地图]
		preg_match_all('/(.*?)\[查看地图\]/', $info->address, $address);//房源地址
		$address = current($address[1])?$address[1][0]:"";
		//高层[查看详情]
		preg_match_all('/(.*?)\[查看详情\]/', $info->building_type, $building_type);//房源类型
		$build_type = current($building_type[1])?$building_type[1][0]:"";
		//60%[查看详情]
		preg_match_all('/(.*?)\[查看详情\]/', $info->gree_rate, $gree_rate);//绿化率
		$green_rate = current($gree_rate[1])?$gree_rate[1][0]:"";
		$green = intval($green_rate);
		//1510户[查看详情]
		preg_match_all('/(.*?)\[查看详情\]/', $info->households, $households);//户数
		$house_holds = current($households[1]) ? $households[1][0] : "";
		$house_holds = intval($house_holds);
		//住宅：70年[查看详情] 		*70  年限
		preg_match_all('/\d+/', $info->volume_rate, $volume_rate);
		$prop_right = current($volume_rate[0])?$volume_rate[0][0]:"";

		/*//3室户型(5)，4室户型(1) 	*3室 4室 户型
		preg_match_all('/([1-9]室|别墅)/', $info->units, $layout);
		$layout = implode(" ",$layout[0]);
		//3室户型(5)，4室户型(1) 	*3室 4室 户型
		preg_match_all('/([1-9]室|别墅)/', $info->units, $layout);
		$da_num=array('零','一','二','三','四','五','六','七','八','九'); 
		$str = "";
		if (count($layout[0]) > 0){
			foreach ($layout[0] as $key => $value) {
				$str .= intval($value) > 0 ? $da_num[intval($value)] . '室 ' : '别墅 ';
			}
		}
		$layout = trim($str) ? trim($str) : '商住户型';*/

		// $str = "3室户型(5)，4室户型(1) 二室 三室 四室 别墅";
		// 三室 四室 二室 别墅 
		$cb_num  = ['/[\x{4e00}]室/u','/[\x{4e09}]室/u','/[\x{4e8c}]室/u','/[\x{56db}]室/u','/[\x{4e94}]室/u','/[\x{516d}]室/u','/[\x{4e03}]室/u','/[\x{516b}]室/u','/[\x{4e5d}]室/u','/[\x{5341}]室/u'];
		$replace = ['1室','2室','3室','4室','5室','6室','7室','8室','9室','10室'];
		$new_str = preg_replace($cb_num, $replace, $info->units);
		preg_match_all('/([1-9]室|别墅)/', $new_str, $layout);
		$arr = array_unique($layout[0]);
		$da_num=array('零','一','二','三','四','五','六','七','八','九'); 
		$str = "";
		if (count($arr) > 0){
			foreach ($arr as $key => $value) {
				$str .= intval($value) > 0 ? $da_num[intval($value)] . '室 ' : '别墅 ';
			}
		}
		$layout = trim($str) ? trim($str) : '商住户型';

		//1812（地下：1812个） 1812
		preg_match_all('/\d+/', $info->car_number, $car_number);
		$car_number = current($car_number[0])?$car_number[0][0]:"";
		$car = intval($car_number);
		//2016-11-20（二批次新推）开盘时间 交房时间 2016-11-20
		preg_match_all('/\d{4}-\d{1,2}-\d{1,2}/', $info->open_time, $open_time);
		$open_time = current($open_time[0])?$open_time[0][0]:"";
		preg_match_all('/\d{4}-\d{1,2}-\d{1,2}/', $info->launch_time, $launch_time);
		$deli_time = current($launch_time[0])?$launch_time[0][0]:"";
		//绕城外-高新-天府新城 高新 
		preg_match_all("|-(.*)-|", $info->region, $region);
		if (count($region[1]) > 0){
			$region = current($region[1])?$region[1][0]:"";
		}else{
			preg_match_all('/(锦江|青羊|金牛|成华|武侯|高新|高新西区|双流|郫县|温江|崇州|龙泉驿|新都|新津|大邑|彭州|都江堰|金堂|邛崃|青白江)/', $info->region, $region);
			$region = current($region[0])?$region[0][0]:"";
		}
		// 住宅：1.8元/m²/月 1.8
		preg_match_all("/\d+(\.\d+)?/", $info->mag_fee, $mag_fee);
		$prop_fee = current($mag_fee[0]) ? $mag_fee[0][0] : 0;

		$city = "成都";
		//获取经纬度
		$lonlat = self::getLonLat($info->title, $city);

		$data = new \stdClass();
		$data->id = $id;
		$data->command = "SHOUSE";
		$data->old_url = $old_url;
		
		//2017-3-29 +
		$data->is_self = 0;
		$data->three_url = $three_url;

		$data->city_id = 63;
		$data->name = $info->title;


		// $data->tags = "";
		$data->cate_id = 1;
		$data->thumb = $info->thumb;
		// $data->pics = "";
		$data->price = $price;
		$data->price_bk = intval($info->price);
		$data->region = $region;
		$data->property = $info->property;
		$data->layout = $layout;
		$data->open_time = $open_time;
		$data->deli_time = $deli_time;
		$data->developers = $info->developers;
		$data->address = $address;
		// $data->sales_phone = "";
		$data->build_type = $build_type;
		$data->house_holds = $house_holds; 
		$data->prop_right = $prop_right;
		$data->prop_comp = $info->pro_company;
		$data->prop_fee = $prop_fee;
		// $data->deco_type = "";
		$data->top_floor = 0;
		$data->car = $car;
		// $data->car_ratio = "";
		// $data->plot = "";
		$data->green = $green;
		$data->lon = $lonlat->lon;
		$data->lat = $lonlat->lat;
		$data->sources = $info->source_site;
		// $data->comment = 0;
		// $data->visit = 0;
		// $data->is_display = 1;
		// $data->is_del = 0;
		// $data->is_self = 0;
		// $data->order_by = 100;
		// $data->create_time = date("Y-m-d H:i:s", time());
		// $data->update_time = date("Y-m-d H:i:s", time()); 

		$redis = Di::getDefault()['redis'];
		$queue = Di::getDefault()['queue'];

		$redis->set("SHOUSE_{$info->id}", $info->id);
		$redis->expireAt("SHOUSE_{$info->id}", time() + 60*5);
		$queue->put(json_encode($data));
		// $info->is_migrate = self::MIGRATE_TRUE;
		// $info->save();

		// $row = new EwHouse;
		// // return $row -> save((array)$data);
		// if ($row->save((array)$data))
		// {
		// 	$info->is_migrate = self::MIGRATE_TRUE;
		// 	$info->save();
		// }
		// if (!$row->save((array)$data))
		// {
		// 	$msg =$row->getMessages();
		// 	var_dump($msg);die;
		// }
	}

	/**
	 * [batchMigrate 批量入库]
	 * @param  [type] $id_arr [description]
	 * @return [type]         [description]
	 */
	public static function batchMigrate($id_arr = [])
	{
		if ($id_arr && is_array($id_arr) && count($id_arr) > 0){
			foreach ($id_arr as $id) {
				self::migrate($id);
			}
		}
	}

	/**
	 * [getLonLat 根据城市和楼盘名称获取经纬度]
	 * @param  [type] $name [description]
	 * @param  [type] $city [description]
	 * @return [type]       [description]
	 */
	public static function getLonLat($name, $city)
	{
		$ak   = "lQGoEIx7wzGrUHyMbgufPhEp00GGcDmR";
		$output = "json";
		$url = "http://api.map.baidu.com/geocoder/v2/?output={$output}&address={$name}&city={$city}&ak={$ak}";
		$json = file_get_contents($url); 
		$obj = json_decode($json);

		$arr = new \stdClass;
		$arr->lon = 0.000000;
		$arr->lat = 0.000000;

		if ($obj->status == 0){
			$arr->lon = round($obj->result->location->lng,6);//经度
			$arr->lat = round($obj->result->location->lat,6);//纬度
		}

		return $arr;
	}
}